const DB = require('../tools/mysql')

module.exports = async ctx => {
  const login_uid = ctx.url.split('?')[1]
  if (ctx.request.body.login === '1') {
    if (global.loginUid) {
      ctx.body = { code: -2 }
      return
    }
    const user = await DB('admin').select('*').where('password', ctx.request.body.pass)
    if (user.length == 0) {
    	ctx.body = { login: false }
    } else {
    	global.loginUid = login_uid
    	global.resetLoginUid = function() {
        clearTimeout(global.loginTimeout)
    		global.loginTimeout = setTimeout(function() {
    			global.loginUid = ''
          clearTimeout(global.heartbeatTimeout)
          global.resetLoginUid = null
    		}, 20 * 60 * 1000)
    	}
    	global.resetLoginUid()
    	ctx.body = { login: true }
    }
  } else if (ctx.request.body.login === '2') {
    if (!global.loginUid) {
      global.resetLoginUid = null
      ctx.body = { login: true }
      return;
    }
    if (global.loginUid == login_uid) {
      global.loginUid = ''
      clearTimeout(global.loginTimeout)
      clearTimeout(global.heartbeatTimeout)
      global.resetLoginUid = null
      ctx.body = { login: true }
    } else {
      ctx.body = { login: false }
    }
  } else if (ctx.request.body.login === '3') {
    if (global.loginUid != login_uid) {
      ctx.body = { code: -5 }
      return
    }
    clearTimeout(global.heartbeatTimeout)
    global.heartbeatTimeout = setTimeout(function() {
      global.loginUid = ''
      clearTimeout(global.loginTimeout)
      global.resetLoginUid = null
    }, 2 * 60 * 1000)
    ctx.body = { code: -3 }
  }
}